<!--
  * 代理商黑名单表
  *
  * @Author:    zzb
  * @Date:      2025-01-23 11:53:35
-->
<template>
  <!-- 查询代理商弹窗 -->
  <a-modal
    title="添加黑名单"
    :width="900"
    :open="searchModalVisible"
    @cancel="onSearchModalClose"
    :footer="null"
    :maskClosable="false"
    :destroyOnClose="true"
  >
    <a-form class="search-form">
      <a-row>
        <a-col :span="24">
          <a-form-item label="输入查询" class="smart-query-form-item">
            <a-input v-model:value="companyAbbrNameLeftLike" placeholder="公司简称" style="width: 300px" />
            <a-input v-model:value="nameLeftLike" placeholder="联系人" style="width: 300px" />
            <a-button type="primary" @click="onSearch" style="margin-left: 8px">查询</a-button>
            <a-button @click="onSearchReset" style="margin-left: 8px">重置</a-button>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <a-table size="small" :dataSource="searchResults" :columns="searchColumns" :pagination="false" :loading="tableLoading">
      <template #index="{ index }">
        {{ (searchPagination.current - 1) * searchPagination.pageSize + index + 1 }}
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'action'">
          <a-button type="link" @click="onAddToBlacklist(record)">加入黑名单</a-button>
        </template>
      </template>
    </a-table>

    <div class="pagination">
      <a-pagination
        v-model:current="searchPagination.current"
        :total="searchPagination.total"
        :show-total="(total) => `共${searchPagination.total}条`"
        :pageSize="searchPagination.pageSize"
        @change="onPageChange"
      />
    </div>
  </a-modal>

  <!-- 拉黑原因弹窗 -->
  <a-modal
    title="拉黑原因"
    :width="500"
    :open="reasonModalVisible"
    @cancel="onReasonModalClose"
    :maskClosable="false"
    :destroyOnClose="true"
    @ok="onReasonSubmit"
  >
    <a-form :model="reasonForm">
      <a-form-item label="拉黑处理" required>
        <!--        <a-select v-model:value="reasonForm.handle" placeholder="请选择">-->
        <!--          <a-select-option -->
        <!--            v-for="item in handleTypeList" -->
        <!--            :key="item.value" -->
        <!--            :value="item.value"-->
        <!--          >-->
        <!--            {{ item.label }}-->
        <!--          </a-select-option>-->
        <!--        </a-select>-->
        <a-select v-model:value="reasonForm.handle" style="width: 180px" allowClear :options="BLACKLIST_AGENT_STATUS" placeholder="拉黑处理" />
      </a-form-item>
      <a-form-item label="拉黑原因" required>
        <a-textarea v-model:value="reasonForm.reason" :rows="4" placeholder="请输入拉黑原因，限60个汉字" :maxlength="60" />
      </a-form-item>
      <a-form-item label="附件">
        <div class="upload-list">
          <div class="upload-item">
            <a-upload
              v-model:fileList="reasonForm.url"
              :customRequest="(file) => uploadFunc(file, 'url')"
              :multiple="false"
              :maxCount="3"
              :accept="limitUpload['url'].fileType.toString()"
              :showUploadList="{ showPreviewIcon: true, showRemoveIcon: true }"
              :before-upload="(file, fileList) => beforeUpload(file, fileList, 'url')"
              list-type="picture-card"
              @change="handleUploadChange"
            >
              <div v-if="reasonForm.url?.length < 3">
                <plus-outlined />
                <div style="margin-top: 8px">上传</div>
              </div>
            </a-upload>
          </div>
        </div>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
  import { reactive, ref, nextTick } from 'vue'
  import { message, Modal, Upload } from 'ant-design-vue'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { agentBlacklistApi } from '/src/api/business/b-operation/agent-blacklist/agent-blacklist-api'
  import { uploadFileOther } from '/@/api/support/file-api.js'
  import { smartSentry } from '/@/lib/smart-sentry'
  import { PlusOutlined } from '@ant-design/icons-vue'
  import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue'
  import { getObjValue, setObjValue, selectDictLabel } from '/@/utils/common.js'
  import { myUpload } from '/@/utils/myUpload'
  import {
    BLACKLIST_AGENT_STATUS, //拉黑状态
  } from '/@/constants/dict'
  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['reloadList'])

  // ------------------------ 显示与隐藏 ------------------------
  // 是否显示
  const searchModalVisible = ref(false)

  function show(rowData) {
    // 显示查询代理商弹窗
    searchModalVisible.value = true
    // 初始化查询
    companyAbbrNameLeftLike.value = ''
    nameLeftLike.value = ''
    searchPagination.current = 1
    onSearch()
  }

  function onClose() {
    searchModalVisible.value = false
    companyAbbrNameLeftLike.value = ''
    nameLeftLike.value = ''
    searchResults.value = []
    searchPagination.current = 1
  }

  // ------------------------ 表单 ------------------------

  // 查询弹窗相关
  const nameLeftLike = ref('')
  const companyAbbrNameLeftLike = ref('')
  const tableLoading = ref(false)
  const searchResults = ref([])
  const searchPagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
  })

  const searchColumns = [
    {
      title: '序号',
      key: 'index',
      slots: { customRender: 'index' },
      width: 60,
    },
    { title: '登录账号', dataIndex: 'no' },
    { title: '公司简称', dataIndex: 'companyAbbrName' },
    { title: '联系人', dataIndex: 'name' },
    { title: '联系方式', dataIndex: 'phone' },
    { title: '操作', dataIndex: 'action', width: 120 },
  ]

  // 拉黑原因弹窗相关
  const reasonModalVisible = ref(false)
  const reasonForm = reactive({
    handle: undefined,
    reason: '',
    url: [],
    selectedAgent: null,
  })

  // 查询代理商
  async function onSearch() {
    tableLoading.value = true
    try {
      const params = {
        companyAbbrNameLeftLike: companyAbbrNameLeftLike.value,
        nameLeftLike: nameLeftLike.value,
        pageNo: searchPagination.current,
        pageSize: searchPagination.pageSize,
      }
      const res = await agentBlacklistApi.queryPageAgent(params)
      searchResults.value = res.data
      searchPagination.total = res.total
    } catch (error) {
      message.error('查询失败')
    } finally {
      tableLoading.value = false
    }
  }

  // 选择加入黑名单
  function onAddToBlacklist(record) {
    reasonForm.selectedAgent = record
    searchModalVisible.value = false
    reasonModalVisible.value = true
  }

  // 提交拉黑原因
  async function onReasonSubmit() {
    console.log('reasonForm上传表单', reasonForm)
    if (!reasonForm.handle) {
      message.error('请选择拉黑处理方式')
      return
    }
    if (!reasonForm.reason) {
      message.error('请输入拉黑原因')
      return
    }

    Modal.confirm({
      title: '确认提示',
      content: `确定要将 "${reasonForm.selectedAgent.companyName}" 加入黑名单吗？加入黑名单后，该代理商将${selectDictLabel(BLACKLIST_AGENT_STATUS, reasonForm.handle)}！`,
      async onOk() {
        SmartLoading.show()
        try {
          const params = {
            agentId: reasonForm.selectedAgent.id, // 代理商ID
            handle: reasonForm.handle, // 处理方式
            reason: reasonForm.reason, // 拉黑原因
            url: reasonForm.url,
          }
          await agentBlacklistApi.add(params)
          message.success('操作成功')
          reasonModalVisible.value = false
          // 重置表单
          onReasonModalClose()
          emits('reloadList')
        } catch (error) {
          smartSentry.captureError(error)
          message.error('操作失败')
        } finally {
          SmartLoading.hide()
        }
      },
    })
  }

  const limitUpload = {
    url: {
      fileType: ['.jpg', '.BMP', '.png', '.jpeg', '.pdf'],
      fileSize: 2,
    },
  }
  // 上传前拦截
  const beforeUpload = (file, fileList, field) => {
    // 校检文件类型
    if (limitUpload[field].fileType.length) {
      const fileExt = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
      const isTypeOk = limitUpload[field].fileType.includes(fileExt)
      if (!isTypeOk) {
        message.warning(`文件格式不正确, 请上传${limitUpload[field].fileType.toString().replace(/\./g, '').replace(/,/g, '、')}格式文件!`)
        return false || Upload.LIST_IGNORE
      }
    }

    // 校检文件大小
    if (limitUpload[field].fileSize) {
      const isLt = file.size / 1024 / 1024 < limitUpload[field].fileSize
      if (!isLt) {
        message.warning(`上传文件大小不能超过 ${limitUpload[field].fileSize} MB!`)
        return false || Upload.LIST_IGNORE
      }
    }

    return true
  }

  // 上传文件自定义的方法
  const uploadFunc = async (file, fieldName) => {
    // 确保获取到文件对象
    const fileObj = file.file
    if (!fileObj) {
      return
    }

    const response = await myUpload(file)
    let arr = getObjValue(reasonForm, fieldName).map((item) => {
      if (item.uid === fileObj.uid) {
        message.success(`${fileObj.name} 上传成功`)
        return response
      }
      return item
    })
    setObjValue(reasonForm, fieldName, arr)
  }
  function handleUploadChange(...data) {
    console.log('data==>', data)
    console.log('reasonForm==>', reasonForm)
  }

  function onSearchModalClose() {
    searchModalVisible.value = false
    nameLeftLike.value = ''
    companyAbbrNameLeftLike.value = ''
    searchResults.value = []
    searchPagination.current = 1
  }

  function onReasonModalClose() {
    reasonModalVisible.value = false
    reasonForm.handle = undefined
    reasonForm.reason = ''
    reasonForm.url = []
    reasonForm.selectedAgent = null
  }

  function onSearchReset() {
    nameLeftLike.value = ''
    companyAbbrNameLeftLike.value = ''
    searchPagination.current = 1
    searchResults.value = []
    onSearch()
  }

  function onPageChange(page) {
    searchPagination.current = page
    onSearch()
  }

  defineExpose({
    show,
  })
</script>

<style lang="less" scoped>
  .smart-query-form-item {
    margin-bottom: 0;

    :deep(.ant-form-item-label) {
      width: 80px;
      text-align: right;
      label {
        color: rgba(0, 0, 0, 0.85);
      }
    }

    :deep(.ant-form-item-control-input) {
      display: flex;
      align-items: center;
    }
  }

  .search-form {
    margin-bottom: 16px;
  }
  .pagination {
    margin-top: 16px;
    text-align: right;
  }
  .upload-list {
    display: flex;
    gap: 16px;
  }
  .upload-item {
    :deep(.ant-upload.ant-upload-select-picture-card) {
      width: 104px;
      height: 104px;
      margin: 0;
    }
    :deep(.ant-upload-list-picture-card-container) {
      width: 104px;
      height: 104px;
    }
  }
</style>
